package com.expires.leecode;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: SpringBootDemos
 * @description: 寻找两个正序数组的中位数 https://leetcode.cn/problems/median-of-two-sorted-arrays/
 * @author: Kangsen
 * @create: 2022-05-30 09:00
 **/

public class MedianSorted {
    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        List<Integer> list = new ArrayList<>(nums1.length + nums2.length);
        for (int i = 0; i < nums1.length; i++) {
            list.add(nums1[i]);
        }
        for (int i = 0; i < nums2.length; i++) {
            list.add(nums2[i]);
        }
        list = list.stream().sorted((o1, o2) -> o1.compareTo(o2)).collect(Collectors.toList());
        int index = (list.size() - 1) / 2;
        if (list.size() % 2 == 0) {
            double sum = list.get(index) + list.get(index + 1);
            return sum/2;
        } else {
            //中位数的下标
            return list.get(index);
        }
    }


    public static void main(String[] args) {
        int[] nums1 = new int[]{1,2}, nums2 = new int[]{3,4};
        double sortedArrays = findMedianSortedArrays(nums1,nums2);
        System.out.println("sortedArrays:"+sortedArrays);
    }
}
